use anyhow::Result;
use clap::{Arg, ArgAction, Command};
use iced::{
    advanced::{
        layout::{Limits, Node},
        mouse::Cursor,
        renderer,
        renderer::Style,
        widget::{text::Text, tree::State, Tree},
        Layout, Widget,
    },
    settings::Settings,
    widget::{button, column, scrollable, text, vertical_space, Column},
    Color, Element, Font, Length, Rectangle, Size, Task, Theme,
};
use khronos_egl::Downcast;
use std::fs;
use std::path::Path;

const CMD_TOPIC_PATH: &str = "topic_path";
pub fn main() -> Result<()> {
    let matches = Command::new("assistant_window")
        .version("0.1.0")
        .author("caozongying<zongying_cao@163.com>")
        .about("caozongying_cao<zongying_cao@163.com> is the author of assistant window")
        .arg(
            Arg::new(CMD_TOPIC_PATH)
                .short('t')
                .long(CMD_TOPIC_PATH)
                .value_name("TOPIC PATH")
                .help("主题路径")
                .action(ArgAction::Set),
        )
        .get_matches();

    let topic_path = Path::new(
        matches
            .get_one::<String>(CMD_TOPIC_PATH)
            .expect(&format!("请提供参数:{}", CMD_TOPIC_PATH)),
    )
    .join("messages");
    let messages_content = fs::read_to_string(topic_path)?;
    let font = Font::with_name("PingFang SC");

    Ok(iced::application("Messages", update, view)
        .settings(Settings {
            default_font: font,
            ..Settings::default()
        })
        .run_with(|| {
            (
                Model {
                    all_messages: messages_content,
                },
                Task::<Message>::none(),
            )
        })?)
}

#[derive(Debug, Clone)]
struct Model {
    all_messages: String,
}

#[derive(Debug, Clone)]
enum Message {
    Increment,
}

fn update(value: &mut Model, message: Message) {
    match message {
        Message::Increment => (),
    }
}

fn view(value: &Model) -> Element<'_, Message> {
    let my_text = TextComponent {
        message: value.all_messages.clone(),
    };

    scrollable(column![text("hello"), my_text.clone().view()]).into()
}

struct TextComponent {
    message: String,
}

impl TextComponent {
    fn update(&mut self, _: Message) {
        // 这里可以定义如何处理消息
    }

    fn view(&self) -> Element<Message> {
        // 创建一个包含文本的列布局
        Column::new()
            .push(text(&self.message).size(30)) // 添加文本组件
            .width(Length::Fill) // 设置宽度为填充
            .height(Length::Fill) // 设置高度为填充
            .into()
    }
}

impl Default for TextComponent {
    fn default() -> Self {
        TextComponent {
            message: String::from("Hello, Iced!"), // 默认文本信息
        }
    }
}
